package com.example.hw_demo.controller;

import com.example.hw_demo.util.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * author  :$[USER]
 * time    :$[DATE] $[TIME]
 * version :vl.0
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${upload.filePath}")
    private String filePath;

    @PostMapping("/upload")
    public Result upload(@RequestParam("file")MultipartFile file){
        // 判断文件是否为空
        if (file == null) {
            return new Result(200,"参数文件为空",null);
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件扩展名，jsp
        String fileExtension = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        // 重新生成的文件名System.currentTimeMillis() 当前时间的毫秒数
        String saveFileName = System.currentTimeMillis() + fileExtension;

        File directory = new File(filePath);
        if (!directory.exists()){
            directory.mkdir();
        }
        // 在指定目录下创建该文件
        File targetFile = new File(directory, saveFileName);
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return  new Result(200,"上传成功,返回图片地址","/images/"+saveFileName);
    }


}
